package cn.com.jtang.wedding.util;

import java.io.File;
import java.net.URL;
import java.util.Iterator;

import org.dom4j.Branch;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class XmlUtil {
	
	private static final SAXReader SAXREADER = new SAXReader();
	private static Element root; 
	
	static{
		String value = null;
		XmlUtil xml = new XmlUtil();
		URL configUrl =xml.getClass().getResource("/config.xml");
		File file = new File(configUrl.getPath());
		Document doc;
		try {
			doc = getDocument(file);
			root = doc.getRootElement();
		} catch (DocumentException e) {
		}
	}
	
	public static String getConfigParameter(String param){

		String value = getChildNodeValueOf(root, param);
		return value;
	}
	
	public static Document getDocument(File file) throws DocumentException {
		return SAXREADER.read(file);
	}
	
	public static String getChildNodeValueOf(Node node, String tagName) {
		if (tagName.equals(node.getName())) {
			return getValueOf(node);
		}
		if (node instanceof Branch) {
			Iterator it = ((Branch) node).content().iterator();
			while (it.hasNext()) {
				Node temp = (Node) it.next();
				if (temp instanceof Element && tagName.equals(temp.getName())) {
					return getValueOf(temp);
				}
			}
		}
		return null;
	}
	
	public static final String getValueOf(Node node) {
		if (node == null) {
			return null;
		}
		return node.getText().trim();
	}

}
